//
// bufdb_server.cpp
// ~~~~~~~~~~~~~~~~~~
//
// Copyright (c) 2010 The bufdb Team
//

#include <ctime>
#include <iostream>
#include <string>
#include <boost/asio.hpp>

#include "database.pb.h"
#include "../client/bufferDB.h"
#include "bufDBServer.h"
#include "../setup/connect.h"

#include <google/protobuf/message.h>
#include <google/protobuf/descriptor.h>
#include <google/protobuf/text_format.h>
using namespace google::protobuf;
using boost::asio::ip::tcp;

void SaveToDatabase(db::Database *msg);

int main(int argc, char *argv[])
{
   bufDBServer *bufServ = new bufDBServer(argc, argv);    
   try
   {
      boost::asio::io_service io_service;

      tcp::endpoint endpoint(tcp::v4(), 13);
      tcp::acceptor acceptor(io_service, endpoint);

      for (;;)
      {
         tcp::iostream stream;
         cerr << "accepting..." << endl;
         acceptor.accept(*stream.rdbuf());

         cerr << "parsing..." << endl;

         // parse the message into the class
         db::Database *msg = new db::Database();
         if (!msg->ParseFromIstream(&stream)) {
            std::cerr << "Failed to parse" << std::endl;
            exit(1);
         }

         cerr << "printing..." << endl;
         msg->PrintDebugString();	  
         cout.flush();

         if (msg->write()) {
            bufServ->SaveToDatabase(msg);
            exit(1);
         } else {
            acceptor.close();
            cerr << "retrieving..." << endl;

            bufServ->RetrieveFromDatabase();

            cerr << "retrieved and closed..." << endl;
            bufServ->msg->set_write(false);
            tcp::iostream stream2("localhost", "daytime");
            bufServ->msg->SerializeToOstream(&stream2);
            stream2.close();

            cerr << "stream sent and closed..." << endl;
            exit(1);
         }
      }
   }
   catch (std::exception& e)
   {
      std::cerr << e.what() << std::endl;
   }

   return 0;
}

